package org.example.cloudapply.controller;

import jakarta.validation.Valid;
import org.apache.ibatis.annotations.Delete;
import org.example.cloudapply.dto.ApplicationDTO;
import org.example.cloudapply.entity.Result;
import org.example.cloudapply.service.ApplicationService;
import org.example.cloudapply.vo.ApplicationVO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/applications")
public class ApplicationController {

    private final ApplicationService applicationService;

    public ApplicationController(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    @PostMapping
    public ResponseEntity<?> submitApplication(@Valid @RequestBody ApplicationDTO dto) {
        try {
            applicationService.processApplication(dto);
            return ResponseEntity.ok("申请提交成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("申请提交失败: " + e.getMessage());
        }
    }

    @GetMapping
    public ResponseEntity<?> getApplications(@RequestParam String openid) {
        try {
            List<ApplicationVO> applications = applicationService.getApplicationsByOpenid(openid);
            return ResponseEntity.ok(applications);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("查询失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{applyId}")
    public Result<?> cancelApplication(@PathVariable Integer applyId) {
        applicationService.deleteScheduleJobsByApplyId(applyId);
        applicationService.cancelApplication(applyId);
        return Result.success();
    }

    @DeleteMapping("time/{applyId}")
    public Result<?> deleteApplication(@PathVariable Integer applyId) {
        // 先回收资源
        // TODO
        //cloudService.recycleInstance(applicationRepository.findById(applyId).getAccountInfo());
        // 再删除记录
        applicationService.cancelApplication(applyId);
        return Result.success();
    }
}